package cn.wolfcode.mq.listener;


import cn.wolfcode.handler.WebSocketServer;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderResultGroup",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
public class OrderResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult result) {
        System.err.println("结果消息处理中。。。");
        System.err.println(result.getToken());
        //1 从结果消息中提取token,从ConcurrentHashMap中获取连接对象
//      WebSocketServer server = WebSocketServer.clients.get(result.getToken());
        WebSocketServer server = null;

        //重试机制
        int count = 10;
        for (int i = 0; StringUtils.isEmpty(server = WebSocketServer.clients.get(result.getToken()))
                && i < count; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果10次也没有获取到
        if (StringUtils.isEmpty(server)) {
            return;
        }
        //2 把结果信息,利用连接对象,发送给前端
        try {
            server.getSession().getBasicRemote().sendText(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关掉长连接
                server.getSession().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
